<template>
	<view class="my-order">
		<u-sticky bgColor="#ffffff">
			<view class="" style="border-bottom: 1px solid #f2f2f2;">
				<u-tabs :list="list1" @change="handleChange" :current="current" :inactiveStyle="{
						'white-space':'nowrap',
						'font-size':'24rpx',
						'color':'#666666'
					}" :activeStyle="{
						'white-space':'nowrap',
						'font-size':'24rpx',
						'color': 'black'
					}" :lineHeight="0" :lineWidth="0" activeStyle="color:rgb(255,149,2);" keyName="name" size="mini"
					:scrollable="false"></u-tabs>
			</view>
		</u-sticky>
		<view class="wrapper">
			<view class="list">
				<view class="list-item" v-for="(item,index) in listData" :key="index">
					<blockquote class="list-item-block" v-if="item.orderType=='TICKET'"
						@click="handleRouter('/homePages/scenicSpot/details',item,2,'details')">
						<blockquote class="padding">
							<view class="title">
								<image class="title-icon" src="/static/icon/home/watch.png" mode="aspectFill"></image>
								<text style="margin: 0 12rpx;">中塔旅游</text>
								<u-icon name="arrow-right" size="15"></u-icon>
							</view>
							<view class="space-between icon-padding-left" style="margin-top:20rpx;">
								<view class="">参观日期：{{item.proDate}}</view>
								<view class="tips" style="color: rgb(245,63,63);font-size: 26rpx;">
									{{item.orderStatueName}}
								</view>
							</view>
							<view class="icon-padding-left" style="padding-bottom:20rpx;">
								<view v-for="(_i,_n) in item.proName" :key="_n"
									style="color:rgb(127,127,127);margin-top:15rpx;">{{_i}}</view>
							</view>
						</blockquote>
						<view class="operate padding"
							v-if="Number(item.orderStatus) == 102 || Number(item.orderStatus) == 10 || Number(item.orderStatus) == 31 || Number(item.orderStatus) == 11 || Number(item.orderStatus) == 14 ||Number(item.orderStatus) == 32 ">
							<view class="many">
								<!-- 只有11状态下没有更多操作 -->
								<text @click.stop="handleMoney(index)"
									v-if="Number(item.orderStatus) != 11 && Number(item.orderStatus) != 31">更多</text>
								<view class="many-list" v-if="operateIndex == index">
									<text class="many-list-item" @click.stop="handleOrdingOperate(item,1)">删除订单</text>
									<text class="many-list-item" v-if="Number(item.orderStatus) == 10"
										@click.stop="handleOrdingOperate(item,2)"
										style="border-top:1px solid #f2f2f2;">取消订单</text>
								</view>
							</view>

							<view
								v-if="Number(item.orderStatus)  == 14 || Number(item.orderStatus) == 32 || Number(item.orderStatus) == 31 || Number(item.orderStatus) == 102"
								class="submit" @click.stop="handleGoBuy(item)">
								再次购买</view>
							<view v-if="Number(item.orderStatus)  == 10" class="submit" @click.stop="handlePay(item)">
								立即支付</view>
							<view v-if="Number(item.orderStatus)  == 11" @click.stop="handleQuit(item)" class="submit">
								申请退票</view>
						</view>
					</blockquote>
					<!-- 酒店 已预约 取消预约 -->
					<blockquote v-if="item.orderType=='HOTEL'">
						<!-- 服化1 -->
						<blockquote class="list-item-block" v-if="false">
							<blockquote class="padding">
								<view class="title">
									<u-icon name="home" size="18"></u-icon>
									<text style="margin: 0 12rpx;">服化服务</text>
									<u-icon name="arrow-right" size="15"></u-icon>
									<view class="tips">待交易</view>
								</view>
								<view class="shopping">
									<image src="/static/phone.png" mode="aspectFill" class="imge"></image>
									<view class="content">
										<text
											class="tips1">卿绕梦原创汉服女夏季送制对襟刺绣长订卿绕梦原创汉服女夏季送制对襟刺绣长订卿绕梦原创汉服女夏季送制对襟刺绣长订卿绕梦原创汉服女夏季送制对襟刺绣长订卿绕梦原创汉服女夏季送制对襟刺绣长订</text>
										<text class="tips2">红色，175/XXL</text>
									</view>
									<view class="price">
										<text>共1件商品</text>
										<text style="color:black;margin-left: 14rpx;font-size: 26rpx;">￥120</text>
									</view>
								</view>
							</blockquote>
							<view class="operate padding">
								<view class="many">
									<text @click="handleMoney(index)">更多</text>
									<view class="many-list" v-if="operateIndex == index">
										<text class="many-list-item" @click="handleOrdingOperate(item,1)">删除订单</text>
										<text class="many-list-item" @click="handleOrdingOperate(item,2)"
											style="border-top:1px solid #f2f2f2;">取消预约</text>
									</view>
								</view>
								<view class="submit" @click.stop="handleRouter('/homePages/hotel/reserve',item,1)">再次预约
								</view>
							</view>
						</blockquote>
						<!-- 服化2 -->
						<blockquote class="list-item-block" v-if="false">
							<blockquote class="padding">
								<view class="title">
									<u-icon name="home" size="18"></u-icon>
									<text style="margin: 0 12rpx;">服化服务</text>
									<u-icon name="arrow-right" size="15"></u-icon>
									<view class="tips">待交易</view>
								</view>
								<view class="shopping">
									<image src="/static/phone.png" mode="aspectFill" class="imge"></image>
									<image src="/static/phone.png" mode="aspectFill" class="imge"></image>

									<view class="price">
										<text>共1件商品</text>
										<text style="color:black;margin-left: 14rpx;font-size: 26rpx;">￥120</text>
									</view>
								</view>
							</blockquote>
							<view class="operate padding">
								<view class="many">
									<text @click="handleMoney(index)">更多</text>
									<view class="many-list" v-if="operateIndex == index">
										<text class="many-list-item" @click="handleOrdingOperate(item,1)">删除订单</text>
										<text class="many-list-item" @click="handleOrdingOperate(item,2)"
											style="border-top:1px solid #f2f2f2;">取消预约</text>
									</view>
								</view>
								<view class="submit" @click="handleRouter('/homePages/hotel/reserve',item,1)">再次预约
								</view>
							</view>
						</blockquote>

						<!-- 酒店 -->
						<blockquote class="list-item-block">
							<blockquote class="padding"
								@click="handleRouter('/homePages/hotel/details',item,1,'details')">
								<view class="title">
									<image class="title-icon" src="/static/icon/home/kied.png" mode="aspectFill">
									</image>
									<text style="margin: 0 12rpx;">梅地亚酒店</text>
									<u-icon name="arrow-right" size="15"></u-icon>
									<view class="tips">{{item.orderStatueName}}</view>
								</view>
								<view class="shopping">
									<view class="content">
										<text class="tips1">{{item.proName}}</text>
										<view class="tips2" style="display: flex;font-size: 24rpx;margin-top: 12rpx;">
											<view class="" style="width: 180rpx;">房间数</view>
											<view class="" style="color: black;">{{item.totalNum}}间
											</view>
										</view>
										<view class="tips2" style="display: flex;font-size: 24rpx;margin-top: 12rpx;">
											<view class="" style="width: 180rpx;">入离日期</view>
											<view class="" style="color: black;">
												<view>{{item.proDate}}</view>
											</view>
										</view>
									</view>
									<view class="price">
										<text
											style="color:black;margin-left: 14rpx;font-size: 26rpx;">￥{{item.totalPrice || 0}}</text>
									</view>
								</view>
							</blockquote>
							<view class="operate padding">
								<view class="many">
									<text @click="handleMoney(index)">更多</text>
									<view class="many-list" v-if="operateIndex == index">
										<text class="many-list-item" @click="handleOrdingOperate(item,1)">删除订单</text>
										<text class="many-list-item" @click="handleOrdingOperate(item,2)"
											v-if="Number(item.orderStatus) != 34"
											style="border-top:1px solid #f2f2f2;">取消预约</text>
									</view>
								</view>
								<view class="submit" @click.stop="handleRouter('/homePages/hotel/reserve',item,1)">再次预约
								</view>
							</view>
						</blockquote>
					</blockquote>
				</view>
				<!-- 数据加载中提示 -->
				<view class="" style="margin: 30rpx 0;" v-if="listLock">
					<u-loading-icon mode="semicircle" text="加载中"></u-loading-icon>
				</view>
				<!-- 当前没有数据提示 -->
				<u-empty mode="order" v-else-if="!listData.length" :marginTop="200" />
			</view>
		</view>

		<!-- 申请退票 -->
		<cancel-vote-reason ref="cancel-vote-reason" @submit="getList('refurbish')"></cancel-vote-reason>
	</view>
</template>
<script>
	import {
		orderList,
		orderDel,
		realmName,
		getTicOrderPageMobile,
		getDetailListByOrderNumMobile,
		refundOfOrder,
		cancelReservation,
		getorcode,
		getOrderByIdDetails,
		cancelTicOrder
	} from "@/http";
	import CancelVoteReason from '@/components/cancelVoteReason';
	import {
		dateFormat
	} from '@/utils/pay.js'
	// orderType:  TICKET中塔  HOTEL门票
	export default {
		name: 'MyOrder',
		components: {
			CancelVoteReason
		},
		data() {
			return {
				current: 0,
				realmName,
				list1: [{
						name: '全部',
						orderStatus: ""
					}, {
						name: '待付款',
						orderStatus: 10
					},
					{
						name: '待使用',
						orderStatus: 11
					},
					{
						name: '已完成',
						orderStatus: 14
					},
					{
						name: '已预约',
						orderStatus: 13
					}
				],
				pageNum: 1,
				orderStatus: null,
				listAllData: [],
				listData: [],
				listLock: false,
				operateIndex: "s",
				_onLoad: false
			}
		},
		onShow() {
			if (this._onLoad) { //刷新列表
				this.getList("refurbish");
			}
		},
		onHide() {
			this._onLoad = true;
		},
		onLoad(options) {
			this.current = Number(options.current);
			this.orderStatus = this.list1[this.current].orderStatus;
			this.onReset();
		},
		onReachBottom() {
			this.pageNum += 1;
			this.getList();
		},
		methods: {
			handleGoBuy(options) { //再次购买
				let data = JSON.parse(JSON.stringify(options));
				delete data.userPhone;
				delete data.userName;
				uni.navigateTo({
					url: `/homePages/scenicSpot/reserve?data=${JSON.stringify(data)}&date=${dateFormat('YYYY-mm-dd',new Date())}`
				});
			},
			handleMoney(index) {
				if (this.operateIndex == index) {
					this.operateIndex = "s";
				} else {
					this.operateIndex = index;
				}
			},
			handlePay(options) { //立即支付
				uni.showLoading({
					title: "正在支付..."
				});
				this.weixinPay(options.totalPrice, `${options.orderNum}`, options);
			},
			async handleQuit(options) {
				let _details = await getOrderByIdDetails({
					storeOrderId: options.storeOrderId,
					orderType: options.orderType
				});
				options.eCodeList = _details.data.data.map(item => item.eCode)
				// eCodeList
				this.$nextTick(() => {
					this.$refs['cancel-vote-reason'].init(options);
				})
			},
			async handleRouter(url, options, status, str) {
				uni.setStorageSync('echo_details', '');
				let _details = await getOrderByIdDetails({
					storeOrderId: options.storeOrderId,
					orderType: options.orderType
				});
				let orderDetailsParmas = {
					dateils: _details.data.data,
					date: _details.data.data[0].proDate,
					productName: _details.data.data[0].proName,
					productId: _details.data.data[0].productId,
					productIsTheatre: _details.data.data[0].productIsTheatre,
					productNum: _details.data.data[0].proCount,
					productPrice: _details.data.data[0].proPrice,
					createTime: options.createTime,
					orderType: options.orderType,
					userCard: options.f1,
					userName: options.userName,
					userPhone: options.userPhone,
					orderId: options.orderNum,
					payPrice: options.totalPrice,
					totalNum: options.totalNum,
					storeOrderId: options.storeOrderId,
					goodsId: options.storeOrderId,
					productCode: _details.data.data[0].proCode
				}
				//status 1再次预约 2
				let data;
				if (options.orderType == "HOTEL") { //已预约 （酒店）
					if (status == 1) {
						let n1 = new Date();
						let n2 = new Date();
						n2.setDate(n2.getDate() + 1);
						data = {
							time: [this._dateFormat('YYYY-mm-dd', n1), this._dateFormat('YYYY-mm-dd', n2)],
							goodsName: _details.data.data[0].goodsName,
							imageUrl: this.realmName + _details.data.data[0].f1,
							f2: options.f2,
							maxInventory: options.maxInventory, //库存
							sellingPrice: options.totalPrice,
							inTime: _details.data.data[0].inTime,
							outTime: _details.data.data[0].outTime,
							arrivePhone: _details.data.data[0].arrivePhone,
							goodsId: options.goodsId,
							storeOrderId: options.storeOrderId
						};
						if (str != 'details') {
							if (data.maxInventory <= 0) return uni.showToast({
								title: "库存不足，无法再次预约",
								icon: "none"
							});
						};
						uni.setStorageSync('order_content', {
							...options,
							remark: _details.data.data[0].remark,
							arrivrTime: _details.data.data[0].arrivrTime
						});
						uni.navigateTo({
							url: `${url}?options=${JSON.stringify(data)}`
						});
					}
				} else if (options.orderType == "TICKET") { //其它状态 中塔
					uni.showLoading({
						title: "加载中..."
					});
					uni.setStorageSync('echo_details', {
						_state: Number(options.orderStatus),
						...orderDetailsParmas
					});
					uni.navigateTo({
						url: `/homePages/scenicSpot/orderDetails`
					});
					uni.hideLoading();
				}
			},
			async handleOrdingOperate(options, status) {
				try {
					let res = null;
					if (status == 1) {
						uni.showLoading({
							title: "正在删除..."
						});
						res = await orderDel(options.storeOrderId);
					}

					if (status == 2) {
						uni.showLoading({
							title: "正在取消..."
						});

						if (options.orderType == 'TICKET') { //中塔
							res = await cancelTicOrder({
								storeOrderId: options.storeOrderId
							});
						} else { //酒店
							res = await cancelReservation({
								storeOrderId: options.storeOrderId
							});
						}
					}
					this.onReset();
					uni.hideLoading();
					this.operateIndex = "s";
				} catch (err) {
					uni.hideLoading();
					this.operateIndex = "s";
				}
			},
			async getList(str) {
				let pageSize = 15,
					pageNum = this.pageNum;
				if (str == "refurbish") {
					pageNum = 1;
					pageSize = this.pageNum * 15;
				} else if (!this.listLock) return;
				let res = await orderList({
					orderSta: Number(this.orderStatus) == 13 ? `${this.orderStatus},99` : this.orderStatus,
					pageNum,
					pageSize,
					userPhone: uni.getStorageSync('phone')
				});
				let data = res.data.rows.map(item => {
					item.proName = item.proName.split(';');
					return item
				})
				if (res.data.rows.length < 15) this.listLock = false;
				if (str != "refurbish") this.listData = [...this.listData, ...data];
				if (str == "refurbish") this.listData = data;
			},
			onReset() {
				this.pageNum = 1;
				this.listData = [];
				this.listLock = true;
				this.getList();
			},
			handleChange({
				orderStatus = 1
			}) {
				this.orderStatus = orderStatus;
				this.operateIndex = 's'
				this.onReset();
			},
			async weixinPay(totalPrice, orderId, options) {
				let _details = await getOrderByIdDetails({
					storeOrderId: options.storeOrderId,
					orderType: options.orderType
				});
				this.$http.getTicketOrderPay({
					payAmount: totalPrice + '',
					thirdOrderId: orderId,
					thirdType: '3',
					payPattern: '1'
				}).then(res => {
					uni.hideLoading();
					let codelist = res.data.weChatPayDTO;
					let that = this
					uni.requestPayment({
						provider: 'wxpay', //
						timeStamp: codelist.timeStamp,
						nonceStr: codelist.nonceStr,
						package: codelist.packageStr,
						signType: 'MD5', //不可变
						paySign: codelist.paySign,
						success: function(res) {
							//支付成功的回调    
							uni.showToast({
								title: '支付成功！',
								icon: 'success'
							}) //付款了才会调下面的接口
							that.$http.setTicketPaySuccess({
								thirdOrderId: orderId,
								thirdType: '3',
								wxPayType: '2'
							}).then(res => {
								that.getList("refurbish");
								if (res.data.code == 200) {
									uni.setStorageSync('echo_details', {
										_state: 2, //1继续支付  2待使用 3已完成
										dateils: _details.data.data,
										date: _details.data.data[0].proDate,
										productName: _details.data.data[0].proName,
										productId: _details.data.data[0].productId,
										productIsTheatre: _details.data.data[0]
											.productIsTheatre,
										productNum: _details.data.data[0].proCount,
										productPrice: _details.data.data[0]
											.proPrice,
										createTime: options.createTime,
										orderType: options.orderType,
										userCard: options.f1,
										userName: options.userName,
										userPhone: options.userPhone,
										orderId: options.orderNum,
										payPrice: options.totalPrice,
										totalNum: options.totalNum,
										storeOrderId: options.storeOrderId,
										goodsId: options.storeOrderId,
										productCode: _details.data.data[0].proCode
									});
									uni.navigateTo({
										url: `/homePages/scenicSpot/orderDetails`
									});
								};
							})
						},
						fail: function(err) {
							//支付失败的回调   
							console.log(err);
						}
					});
				})
			},
			_dateFormat(fmt, date) {
				let ret;
				const opt = {
					"Y+": date.getFullYear().toString(), // 年
					"m+": (date.getMonth() + 1).toString(), // 月
					"d+": date.getDate().toString(), // 日
					"H+": date.getHours().toString(), // 时
					"M+": date.getMinutes().toString(), // 分
					"S+": date.getSeconds().toString() // 秒
					// 有其他格式化字符需求可以继续添加，必须转化成字符串
				};
				for (let k in opt) {
					ret = new RegExp("(" + k + ")").exec(fmt);
					if (ret) {
						fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
					}
				}
				return fmt;
			},
		},
		filters: {
			YYYY_MM_DD_ZH(date) {
				if (!date) return '';
				let fmt = "YYYY-mm-dd HH:MM:SS";
				date = new Date(date);
				let ret;
				const opt = {
					"Y+": date.getFullYear().toString(), // 年
					"m+": (date.getMonth() + 1).toString(), // 月
					"d+": date.getDate().toString(), // 日
					"H+": date.getHours().toString(), // 时
					"M+": date.getMinutes().toString(), // 分
					"S+": date.getSeconds().toString() // 秒
					// 有其他格式化字符需求可以继续添加，必须转化成字符串
				};
				for (let k in opt) {
					ret = new RegExp("(" + k + ")").exec(fmt);
					if (ret) {
						fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
					}
				}
				return fmt;
			},
			ARRIVR_TIME(date) {
				if (!date) return '';
				let fmt = "HH:MM";
				date = new Date(date);
				let ret;
				const opt = {
					"Y+": date.getFullYear().toString(), // 年
					"m+": (date.getMonth() + 1).toString(), // 月
					"d+": date.getDate().toString(), // 日
					"H+": date.getHours().toString(), // 时
					"M+": date.getMinutes().toString(), // 分
					"S+": date.getSeconds().toString() // 秒
					// 有其他格式化字符需求可以继续添加，必须转化成字符串
				};
				for (let k in opt) {
					ret = new RegExp("(" + k + ")").exec(fmt);
					if (ret) {
						fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
					}
				}
				return fmt;
			},
			MM_DD(date) {
				if (!date) return '';
				let fmt = "mm/dd";
				date = new Date(date);
				let ret;
				const opt = {
					"Y+": date.getFullYear().toString(), // 年
					"m+": (date.getMonth() + 1).toString(), // 月
					"d+": date.getDate().toString(), // 日
					"H+": date.getHours().toString(), // 时
					"M+": date.getMinutes().toString(), // 分
					"S+": date.getSeconds().toString() // 秒
					// 有其他格式化字符需求可以继续添加，必须转化成字符串
				};
				for (let k in opt) {
					ret = new RegExp("(" + k + ")").exec(fmt);
					if (ret) {
						fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
					}
				}
				return fmt;
			},
			MONEY_DAY(options) {
				const time = (date1, date2) => {
					let numb = date2.getTime() - date1.getTime();
					let min = numb / 1000 / 60;
					let s = numb / 1000;
					let hours = numb / 1000 / 60 / 60;
					let day = numb / 1000 / 60 / 60 / 24;
					let mon = numb / 1000 / 60 / 60 / 24 / 30;
					return `${Math.ceil(day)}`
				};
				return time(new Date(options.inTime), new Date(options.outTime));
			}
		}
	}
</script>
<style>
	page {
		background-color: #f2f2f2;
	}
</style>
<style lang="scss" scoped>
	.list-item-block {
		background-color: #FFFFFF;
		margin-top: 20rpx;
	}

	.shopping {
		display: flex;
		padding: 24rpx 0;
		position: relative;

		.price {
			position: absolute;
			right: 0;
			bottom: 14rpx;
			color: rgb(170, 170, 170);
			font-size: 28rpx;
		}

		.imge {
			width: 200rpx;
			height: 200rpx;
			margin-right: 30rpx;
		}

		.content {
			flex: 1;

			.tips1 {
				font-size: 26rpx;
				color: #333333;
				display: block;

				width: 485rpx;
				overflow: hidden;
				white-space: nowrap;
				word-wrap: break-word;
				text-overflow: ellipsis;
				-webkit-line-clamp: 1; //行数
				-webkit-box-orient: vertical
			}

			.tips2 {
				display: block;
				margin-top: 20rpx;
				font-size: 26rpx;
				color: rgb(170, 170, 170);
			}
		}
	}

	.operate {
		display: flex;
		align-items: center;
		justify-content: space-between;
		border-top: 1px solid #f2f2f2;
		padding: 24rpx 0rpx;
		font-size: 28rpx;
		color: #333333;

		.many {
			position: relative;

			.many-list {
				position: absolute;
				left: 0rpx;
				border-radius: 12rpx;
				top: 50rpx;
				padding: 4rpx 14rpx;
				white-space: nowrap;
				background-color: #FFFFFF;
				box-shadow: 0 0 4px #cccccc;
				font-size: 24rpx;
				display: flex;
				flex-direction: column;
				z-index: 99;

				.many-list-item {
					padding: 14rpx 0;
				}
			}
		}

		.submit {
			padding: 12rpx 24rpx;
			border-radius: 8rpx;
			font-size: 24rpx;
			border: 1px solid #cccccc;
		}
	}

	.space-between {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.icon-padding-left {
		// padding-left: 46rpx;
	}

	.my-order {
		padding-bottom: 200rpx;

		.wrapper {
			.list {
				.list-item {
					.title {
						color: #333333;
						font-size: 30rpx;
						display: flex;
						align-items: center;
						position: relative;
						padding-top: 20rpx;

						.title-icon {
							width: 50rpx;
							height: 50rpx;
						}

						.tips {
							position: absolute;
							right: 0rpx;
							top: 50%;
							font-size: 26rpx;
							color: rgb(245, 63, 63);
							transform: translate(0, -50%);
						}
					}
				}
			}
		}
	}

	.padding {
		padding-left: 20rpx;
		padding-right: 20rpx;
	}
</style>
